package fr.teuteuf.runstickmanrun.screen;

import tv.ouya.console.api.OuyaController;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Input.Keys;
import com.badlogic.gdx.Net.HttpMethods;
import com.badlogic.gdx.Net.HttpRequest;
import com.badlogic.gdx.Net.HttpResponse;
import com.badlogic.gdx.Net.HttpResponseListener;
import com.badlogic.gdx.controllers.Controller;
import com.badlogic.gdx.graphics.GL10;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.utils.Array;
import com.badlogic.gdx.utils.Json;

import fr.teuteuf.runstickmanrun.Constants;
import fr.teuteuf.runstickmanrun.RunStickmanRun;
import fr.teuteuf.runstickmanrun.Score;

public class ScoreScreen extends AbstractScreen {
	
	private final int NB_MENU_ITEMS = 2;
	
	private OrthographicCamera interfaceCamera;
	private SpriteBatch interfaceBatch;
	
	private Array<Score> leaderBoard;
	private boolean loadingFailed;
	private int menuPicker;
	private float totalTimeElapsed;
	
	public ScoreScreen(RunStickmanRun runStickmanRun) {
		this.runStickmanRun = runStickmanRun;
	}

	@Override
	public void create() {
		super.create();
		reinit();
	}

	@Override
	public void reinit() {
		menuPicker = -1;
		totalTimeElapsed = 0;
		leaderBoard = new Array<Score>();
		loadingFailed = false;
		updateLeaderBoard();

		interfaceCamera = new OrthographicCamera();
		interfaceCamera.setToOrtho(false, Constants.WIDTH_RESOLUTION, Constants.HEIGHT_RESOLUTION);
		interfaceBatch = new SpriteBatch();
	}

	@Override
	public void update(float elapsedTime) {
		interfaceCamera.update();
		totalTimeElapsed += elapsedTime;
	}

	@Override
	public void render() {
		Gdx.gl.glClearColor(0, 0, 0, 1);
		Gdx.gl.glClear(GL10.GL_COLOR_BUFFER_BIT);
		
		interfaceBatch.setProjectionMatrix(interfaceCamera.combined);
		interfaceBatch.begin();
		defaultFont.draw(interfaceBatch, "Run, Stickman, Run!", Constants.WIDTH_RESOLUTION/2 - 100, Constants.HEIGHT_RESOLUTION - 100);
		defaultFont.draw(interfaceBatch, "Your score: "+runStickmanRun.getLastScore()+" - Highscore for this session: "+runStickmanRun.getHighScore(), Constants.WIDTH_RESOLUTION/2 - 175, Constants.HEIGHT_RESOLUTION - 130);
		if(leaderBoard.size > 0) {
			defaultFont.draw(interfaceBatch, "Leaderboard - TOP10:", Constants.WIDTH_RESOLUTION/2 - 100, Constants.HEIGHT_RESOLUTION - 200);
			for(int i = 0; i < leaderBoard.size && i < 10; i++) {
				defaultFont.draw(interfaceBatch, leaderBoard.get(i).getUsername(), Constants.WIDTH_RESOLUTION/2 - 150, Constants.HEIGHT_RESOLUTION - 230 - 20 * i);
				defaultFont.draw(interfaceBatch, Integer.toString(leaderBoard.get(i).getScore()), Constants.WIDTH_RESOLUTION/2 + 50, Constants.HEIGHT_RESOLUTION - 230 - 20 * i);
			}
		} else if(! loadingFailed) {
			defaultFont.draw(interfaceBatch, "Loading leaderboard...", Constants.WIDTH_RESOLUTION/2 - 100, Constants.HEIGHT_RESOLUTION - 200);
		}
		if(loadingFailed || leaderBoard.size > 0) {
			if((int)(totalTimeElapsed * 5) % 2 == 0) {
				if(menuPicker > -1) {
					defaultFont.draw(interfaceBatch, ">>", Constants.WIDTH_RESOLUTION/2 - 150, 200 - menuPicker * 30);
				} else {
					defaultFont.draw(interfaceBatch, "<<", Constants.WIDTH_RESOLUTION/2 - 150, 200 - menuPicker * 30);
					defaultFont.draw(interfaceBatch, ">>", Constants.WIDTH_RESOLUTION/2 + 75, 200 - menuPicker * 30);
				}
			}
			defaultFont.draw(interfaceBatch, "DIFFICULTY = "+runStickmanRun.getSelectedLevel(), Constants.WIDTH_RESOLUTION/2 - 90, 230);
			defaultFont.draw(interfaceBatch, "[RETRY]", Constants.WIDTH_RESOLUTION/2 - 70, 200);
			defaultFont.draw(interfaceBatch, "[HOME SCREEN]", Constants.WIDTH_RESOLUTION/2 - 95, 170);
		}
		defaultFont.draw(interfaceBatch, "User: "+runStickmanRun.getUsername(), 20, 20);
		
		interfaceBatch.end();
	}

	@Override
	public void dispose() {
	}

	@Override
	public boolean keyDown(int keycode) {
		if (runStickmanRun.isOnOuya() && keycode == OuyaController.BUTTON_DPAD_UP
				|| ! runStickmanRun.isOnOuya() && keycode == Keys.UP) {
			if (menuPicker > -1) {
				menuPicker = (menuPicker - 1) % NB_MENU_ITEMS;
			}
		} else if (runStickmanRun.isOnOuya() && keycode == OuyaController.BUTTON_DPAD_DOWN 
				|| ! runStickmanRun.isOnOuya() && keycode == Keys.DOWN) {
			if (menuPicker < NB_MENU_ITEMS - 1) {
				menuPicker = (menuPicker + 1) % NB_MENU_ITEMS;
			}
		} else if (runStickmanRun.isOnOuya()&& keycode == OuyaController.BUTTON_O
				|| ! runStickmanRun.isOnOuya() && keycode == Keys.ENTER) {
			if (menuPicker == 0) {
				runStickmanRun.changeCurrentScreen(RunStickmanRun.INDEX_SINGLEPLAYER_SCREEN, true);
			} else if (menuPicker == 1) {
				runStickmanRun.changeCurrentScreen(RunStickmanRun.INDEX_HOME_SCREEN, true);
			}
		} else if(runStickmanRun.isOnOuya() && keycode == OuyaController.BUTTON_DPAD_LEFT
		  ||    ! runStickmanRun.isOnOuya() && keycode == Keys.LEFT) {
			if(menuPicker == -1 && runStickmanRun.getSelectedLevel() > 0) {
				runStickmanRun.setSelectedLevel(runStickmanRun.getSelectedLevel() - 1);
			}
		} else if(runStickmanRun.isOnOuya() && keycode == OuyaController.BUTTON_DPAD_RIGHT
		  ||    ! runStickmanRun.isOnOuya() && keycode == Keys.RIGHT) {
			if(menuPicker == -1 && runStickmanRun.getSelectedLevel() < Constants.DIFFICULTY_MAX) {
				runStickmanRun.setSelectedLevel(runStickmanRun.getSelectedLevel() + 1);
			}
		}
		
		return true;
	}
	
	public Array<Score> updateLeaderBoard() {
		final HttpRequest httpGet = new HttpRequest(HttpMethods.GET);
		httpGet.setUrl("http://run-stickman-run.appspot.com/scoresServlet");
		Gdx.net.sendHttpRequest(httpGet, new HttpResponseListener() {
			@Override
			public void failed(Throwable t) {
				loadingFailed = true;
			}
			@Override
			public void handleHttpResponse(HttpResponse httpResponse) {
				String resultString = httpResponse.getResultAsString();
				resultString = resultString.replace("[", "");
				resultString = resultString.replace("]", "");
				String[] tabStrings = resultString.split(",");
				Json json = new Json();
				int i = 0;
				while(i < tabStrings.length) {
					leaderBoard.add(json.fromJson(Score.class, tabStrings[i++]+","+tabStrings[i++]));
				}
				leaderBoard.sort();
			}
		});
		
		return leaderBoard;
	}

	@Override
	public boolean buttonDown(Controller arg0, int arg1) {
		keyDown(arg1);
		return true;
	}
}
